package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.ServiceTypeManager;
import com.xyzh05.model.ServiceType;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class ServiceTypeAction extends BaseAction implements Preparable {
    private ServiceTypeManager serviceTypeManager;
    private List serviceTypes;
    private ServiceType serviceType;
    private Long stId;
    private String query;

    public void setServiceTypeManager(ServiceTypeManager serviceTypeManager) {
        this.serviceTypeManager = serviceTypeManager;
    }

    public List getServiceTypes() {
        return serviceTypes;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String serviceTypeId = getRequest().getParameter("serviceType.stId");
            if (serviceTypeId != null && !serviceTypeId.equals("")) {
                serviceType = serviceTypeManager.get(new Long(serviceTypeId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        serviceTypes = serviceTypeManager.search(query, ServiceType.class);
        return SUCCESS;
    }

    public void setStId(Long stId) {
        this.stId = stId;
    }

    public ServiceType getServiceType() {
        return serviceType;
    }

    public void setServiceType(ServiceType serviceType) {
        this.serviceType = serviceType;
    }

    public String delete() {
        serviceTypeManager.remove(serviceType.getStId());
        saveMessage(getText("serviceType.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (stId != null) {
            serviceType = serviceTypeManager.get(stId);
        } else {
            serviceType = new ServiceType();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (serviceType.getStId() == null);

        serviceTypeManager.save(serviceType);

        String key = (isNew) ? "serviceType.added" : "serviceType.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}